package com.li.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.li.model.RegionStates;
import com.li.service.CsvDataService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Controller
public class ShowController {
    @Resource
    private CsvDataService data;
    private int num=10;
    @RequestMapping("/showall")
    public String show(@RequestParam(value = "country",required=false) String country, @RequestParam(value = "page",required=false) String page, Model model) throws JsonProcessingException {
        List<RegionStates> allStats;
        ObjectMapper mapper=new ObjectMapper();
        if(country == null || country.equals("all") || country.equals("null"))
            allStats=data.getAllRegionStates();
        else
            allStats=data.getAllRegionStates()
                    .parallelStream()
                    .filter(RegionStates->RegionStates.getCountry().equals(country))
                    .collect(Collectors.toList());
        allStats=selectStates(page,allStats,model);
        model.addAttribute("RegionStatesLists", allStats);
        model.addAttribute("states",mapper.writeValueAsString(allStats));
        model.addAttribute("country",country);
        model.addAttribute("time",showTime());
        return "index3";
    }

    public List<RegionStates> selectStates(String page,List<RegionStates> allStates,Model model){
        int currentPage=1;
        int maxPage=allStates.size()/num+1;
        List<RegionStates> showStates=new ArrayList<>();
        if(page!=null)
            currentPage=Integer.parseInt(page);
        if(currentPage<=0)
            currentPage=1;
        if(currentPage>maxPage)
            currentPage=maxPage;
        int start=(currentPage*num-num)>allStates.size()?((currentPage-1)*num-num):(currentPage*num-num);
        int end=start+num;
        while(start<end&&start<allStates.size()){
            showStates.add(allStates.get(start));
            start++;
        }
        model.addAttribute("lastpage",maxPage);
        model.addAttribute("currentpage",currentPage);
        return showStates;

    }

    public String showTime(){
        SimpleDateFormat df = new SimpleDateFormat("yyyy年MM月dd日");
        Date date = new Date();
        date.getTime();
        String time=df.format(date);
        return time;
    }
}


